module Nodes.NodeAdder exposing (..)
import Html exposing (Html,div,text,input,br,button,select,option)
import Html.Attributes exposing (value)
import Html.Events exposing (onClick,onInput)
import Http
import Json.Encode as Encode
import Json.Decode as Decode
import Utils
import Navigation

type Msg 
 = None
 | AddNodeResult (Result Http.Error (Result String String))
 | Confirm
 | InputTitle String
 | InputIsArticle String


type Model = Model NodeId Title IsArticle Log

initModel : NodeId -> Model
initModel nodeId = Model nodeId "" "1" ("NodeAdder: NodeId=" ++ toString nodeId)


type alias Title = String
type alias IsArticle = String
type alias Log = String
type alias NodeId = Int

inputIsArticle : String -> Msg
inputIsArticle int = InputIsArticle int

view : Model -> Html Msg
view ((Model nodeId title isArticle log) as model) =
 let 
  optIsArticle = option [value "1"] [text "文章"]
  optNotArticle = option [value "0"] [text "目录"]
  selector = select [onInput InputIsArticle] [optIsArticle,optNotArticle]
 in 
  div []
   [ text "添加节点"
   , br [] []
   , text "Title" , input [onInput InputTitle] []
   , br [] []
   , text "IsArticle" ,selector
   , br [] []
   , button [onClick Confirm] [text "确认添加"]
   , br [] []
   , text ("NodeAdder: " ++ log) ]

sendAddNode : NodeId -> Title -> IsArticle -> Cmd Msg
sendAddNode nodeId title isArticle =
 let 
  url = "/nodes/" ++ toString nodeId
  body = Http.jsonBody (Encode.object [("title",Encode.string title),("isArticle",Encode.string isArticle)])
  decoder = Decode.oneOf [Decode.map Ok (Decode.field "ok" Decode.string),Decode.map Err (Decode.field "err" Decode.string)]
  request = Utils.put url body decoder 
 in Http.send AddNodeResult request

update : Msg -> Model -> (Model,Cmd Msg)
update msg ((Model nid title isArticle log) as model) =
 case msg of
  Confirm ->
   (Model nid title isArticle (log ++ " 确认添加节点 "),sendAddNode nid title isArticle)

  AddNodeResult res ->
   case res of
    Ok res -> 
     case res of
      Ok _ -> (Model nid title isArticle (log ++ " 添加节点成功 "),Navigation.back 1)
      Err str -> (Model nid title isArticle ("添加节点失败" ++ str),Cmd.none)
    Err err -> (Model nid title isArticle (log ++ " 添加节点失败: " ++ toString err) ,Cmd.none)
  
  InputTitle str -> (Model nid str isArticle log,Cmd.none)

  InputIsArticle str -> (Model nid title str (log ++ " 触发inputisarticle:" ++ str),Cmd.none)

  None -> (model,Cmd.none)